
<template>
  <el-container>
    <el-main>
      <pure-table-area>
        <template #header>
          <div class="flex  ">
            <ProcessPanel
              :key="'stand'"
              :active-button="defaultCode"
              active-panel-name="stand"
              :show-header="showApprovalPanel"
              @click="changeProcess"
            >
              <el-row class="approval-main-header p-16">
                <el-col :span="1">
                  <JYWCaretButton @click="showApprovalPanel = !showApprovalPanel" />
                </el-col>
                <el-col :span="11">
                  <search v-model="searchValue" class="base-margin-right" style="width: 200px" />
                </el-col>
                <el-col :span="12" style="text-align: right">
                  <!-- <pure-button size="mini" label="导出" type="wire-frame" /> -->
                  <pure-button
                    size="mini"
                    label="新增项目"
                    @click="addProject"
                  />
                </el-col>
              </el-row>
            </ProcessPanel>
          </div>
        </template>
        <template #body>
          <div ref="tableWrapper" class="table-wrapper">
            <el-table
              ref="table"
              v-loading="loading"
              :data="data"
              border
              :cell-style="tableStyle.cellStyle"
              :empty-text="emptyText"
              :max-height="tableMaxHeight"
              @filter-change="filterChange"
            >
              <el-table-column
                v-for="(v, i) in tableColumn"
                :key="i"
                :label="v.label"
                :type="v.type"
                :property="v.property"
                :width="v.w"
                :fixed="v.fixed"
                align="center"
                :formatter="v.computed"
                :filters="v.filter"
                :column-key="v.property"
                show-overflow-tooltip
              >
                <template v-if="v.slot" #default="scope">
                  <TableOptionsMenu
                    :data="scope.row"
                    @click="clickOptions($event, scope.row)"
                  />
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
        <template #footer>
          <el-pagination
            :current-page="currentPage"
            :page-sizes="pageSizes"
            :page-size="pageSize"
            :layout="layout"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </template>
      </pure-table-area>
    </el-main>
  </el-container>
</template>

<script>
import {
  mixins_base,
  mixins_project_index,
  mixins_task,
} from '@/minxins/project/index';
import mixin from './mixin';
import { mapMutations, mapState, } from 'vuex';
import ProjectAPI from '@/apis/project';
import { arrayToString, } from '@/utils/common';
import tableStyle from '../style/table';
import PaginationTable from '@/minxins/common/paginationTable';
import ProcessPanel from '@/views/project/components/navigationPanel/processPanel.vue';
import drawerWidth from '@/views/project/common/width/drawer';
import dialogWidth from '@/views/project/common/width/dialog';
export default {
  name: 'XmXmlxps',
  components: {
    ProcessPanel,
    Search: () => import('@/components/input/search.vue'),
    // eslint-disable-next-line vue/no-unused-components
    ItemSet: () => import('../components/panelsGroup/itemSet.vue'),
    // eslint-disable-next-line vue/no-unused-components
    Research: () => import('../components/panelsGroup/research.vue'),
    // eslint-disable-next-line vue/no-unused-components
    Review: () => import('../components/panelsGroup/review.vue'),
    // eslint-disable-next-line vue/no-unused-components
    EditLookOrder: () => import('../components/panelsGroup/reviewPlan.vue'),
    TableOptionsMenu: () => import('./components/optionsMenu.vue'),
    // eslint-disable-next-line vue/no-unused-components
    HandlePanel: () => import('../components/panelsGroup/handlePanel.vue'),
    // eslint-disable-next-line vue/no-unused-components
    End: () => import('../components/task/end.vue'),
    // eslint-disable-next-line vue/no-unused-components
  },

  mixins: [mixins_base, mixins_project_index, mixins_task, mixin, PaginationTable],
  data() {
    return {
      tableStyle,
      showApprovalPanel: true,
      defaultCode: 'stand',
      tableData: [],
      need_code: '',
      visibles: {
        visible: false,
        endVisible: false,
      },
      componentName: '',
      isSubmit: false,
      listApi: ProjectAPI.setUp.getListData,
      isInit: false,
      panelArguments: {
        ItemSet: {
          width: drawerWidth.small_px,
          null: {
            width: drawerWidth.small_px,
          },
          end_termination: {
            width: drawerWidth.small_px,

          },
          item_program_review: {
            width: drawerWidth.small_px,
          },
          item_establish: {
            width: drawerWidth.larger_pr,
          },
          program_review_reject: {
            width: drawerWidth.small_px,
          },
          implement_start: {
            width: drawerWidth.small_px,
          },
          implement_over: {
            width: drawerWidth.small_px,
          },
          item_before_project: {
            width: drawerWidth.small_px,
          },
          end_project: {
            width: drawerWidth.small_px,
          },
          reject_end: {
            width: drawerWidth.small_px,
          },
          props: {
            title: '新增项目',
            hiddenSaveButton: true,
            showFooter: true,
            showTimeLine: true,
          },
        },
        Research: {
          width: drawerWidth.larger_pr,
          item_establish: {
            width: drawerWidth.larger_pr,
          },
          props: {
            title: '调研',
            hiddenSaveButton: true,
            showFooter: true,
          },
        },
        EditLookOrder: {
          width: drawerWidth.larger_pr,
          item_program_review: {
            width: drawerWidth.larger_pr,
          },
          item_before_project: {
            width: drawerWidth.larger_pr,
          },
          implement_over: {
            width: drawerWidth.larger_pr,
          },
          props: {
            title: '评审',
            hiddenSaveButton: true,
            showFooter: true,
          },
        },
      },
    };
  },
  computed: {
    ...mapState('login', {
      myId: (v) => {
        return Number(v.userInfo.id) || 0;
      },
    }),
  },
  activated() {
    this.renderRouteQueryParamsPanel();
  },
  mounted() {
    // this.renderRouteQueryParamsPanel();
    this.DISPATCHT_GET_USER_LIST();
    this.queryCondition.code = this.defaultCode;
    this.currentPage = 1;
    this.queryCondition.pageNum = this.currentPage;
    this.fetchData();
  },
  methods: {
    ...mapMutations('project/index', ['SET_CONFIRM_REVIEW', 'SET_TASK_PERMISSION_NAME']),

    onDone() {
      this.fetchData();
      this.FETCH_PERFORM_EVENT({ name: 'process', });
    },

    /**
     * 针对查看操作的处理
     */
    perviewOptions(type) {
      let componentName = '';
      this.SET_PANCEL_DISABLED({ name: 'needInfo', disabled: true, });
      this.SET_PANCEL_DISABLED({ name: 'researchViewPlan', disabled: true, });
      this.SET_PANCEL_DISABLED({ name: 'projectInfo', disabled: true, });
      this.SET_PANCEL_DISABLED({ name: 'researchInfo', disabled: true, });
      const searchResult = [
        {
          memo: '(方案编辑 => 需求 + 调研)/',
          type: ['item_establish'],
          componentName: 'Research',
        },
        {
          memo: '(项目实施)/(项目结束)/(方案制定=> 评审)',
          type: [
            'implement_start',
            'item_before_project',
            'item_program_review',
            'implement_over',
            'reject_end',
            'end_termination'
          ],
          componentName: 'ItemSet',
        }
      ];
      for (const i of searchResult) {
        if (i.type.includes(type)) {
          componentName = i.componentName;
          break;
        } else {
          componentName = 'ItemSet';
        }
      }
      this.panelArguments[componentName].props.title = '查看';
      this.panelArguments[componentName].props.showFooter = false;

      if (['item_before_project', 'program_review_reject', 'end_project', 'implement_over', 'item_program_review', 'implement_start', null, 'null', 'reject_end', 'end_termination'].includes(type)) {
        if (this.getterPanelGroupData.demand) {
          this.panelArguments[componentName][type].width = drawerWidth.larger_pr;
        } else {
          this.panelArguments[componentName][type].width = drawerWidth.small_px;
          this.panelArguments.ItemSet.props.showTimeLine = true;
        }
      }

      this.renderPanelFn(
        componentName,
        this.panelArguments[componentName][type].width,
        this.panelArguments[componentName].props
      );
    },
    renderRouteQueryParamsPanel() {
      if (this.$route.params.itemCode) {
        this.clickOptions('search', this.$route.params);
      }
    },

    optionsDelete(row) {
      this.$confirm(`是否删除「${row.title}」?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        try {
          await ProjectAPI.setUp.del(row.id);
          this.onDone();
        } catch (e) {
          this.$message.error(e);
        }
      }).catch(() => {});
    },
    optionsEnd(row) {
      this.$dialog({
        title: '终止',
        subTitle: `项目编号:${row.itemCode}`,
        position: 'center',
        width: dialogWidth.small_px,
        component: () => <End onDone={this.onDone} />,
      });
    },
    optionsBack(row) {
      this.$confirm('正在执行撤销操作, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        try {
          await ProjectAPI.base.backItem(row.itemCode);
          this.onDone();
        } catch (e) {
          this.$message.error(e);
        }
      }).catch(() => {});
    },

    async clickOptions(v, r) {
      this.SET_ITEM_CODE(r.itemCode);
      if (['end', 'del', 'back'].includes(v)) {
        if (v === 'end') {
          this.optionsEnd(r);
        } else if (v === 'del') {
          this.optionsDelete(r);
        } else if (v === 'back') {
          this.optionsBack(r);
        } else {
        //
        }
        return;
      }
      let title = '';
      let componentName = '';
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      const showState = r.showState;
      await this.FETCEH_RESET_PANCEL_DISABLED_OPTIONS();
      try {
        const result = await ProjectAPI.setUp.reviewInfo(r.itemCode);
        await this.FETCH_PANEL_DATA(result);
        this.SET_RESEARCH_INFO({ ...r, });
        loading.close();

        if (v !== 'edit' && v !== 'set') {
          this.SET_LOOK_TASK(true);
        } else {
          this.SET_LOOK_TASK(false);
        }

        switch (v) {
          case 'search':
            this.perviewOptions(showState);
            return;
            // 编辑状态
          case 'edit':
            componentName = 'ItemSet';
            this.panelArguments[componentName].props.showTimeLine = true;
            title = '编辑';
            this.SET_PANCEL_DISABLED({ name: 'needInfo', disabled: true, });
            this.SET_PANCEL_DISABLED({ name: 'researchInfo', disabled: true, });
            this.SET_TASK_PERMISSION_NAME('');
            // 判断是否是项目负责人 还是项目的创建人
            if (Number(r.principal) === this.myId || Number(r.createUser === this.myId)) {
              this.SET_TASK_PERMISSION_NAME('leader');
              this.SET_PANCEL_DISABLED({ name: 'projectInfo', disabled: false, });

            // 判断是否是 项目参与人员
            } else if (r.joinUser?.includes(this.myId)) {
              this.SET_TASK_PERMISSION_NAME('join');
              this.SET_PANCEL_DISABLED({ name: 'projectInfo', disabled: true, });
            // 判断是否是该项目的任务成员
            } else if (r.users?.includes(this.myId)) {
              this.SET_PANCEL_DISABLED({ name: 'projectInfo', disabled: true, });
            }

            break;
          case 'set':
            title = '方案制定';
            componentName = 'ItemSet';
            this.panelArguments[componentName].props.showTimeLine = true;

            // 判断是否是项目负责人’
            if (Number(r.principal) === this.myId || Number(r.createUser === this.myId)) {
              this.SET_TASK_PERMISSION_NAME('leader');
            // 判断是否是 项目参与人员
            } else if (r.joinUser?.includes(this.myId)) {
              this.SET_TASK_PERMISSION_NAME('join');

              this.SET_PANCEL_DISABLED({ name: 'projectInfo', disabled: true, });
            // 判断是否是该项目的任务成员
            } else if (r.users?.includes(this.myId)) {
              this.SET_PANCEL_DISABLED({ name: 'projectInfo', disabled: true, });
            }

            this.SET_PANCEL_DISABLED({ name: 'needInfo', disabled: true, });
            this.SET_PANCEL_DISABLED({ name: 'researchInfo', disabled: true, });
            break;
          case 'research':
            this.componentName = 'Research';
            break;
          case 'review':
            this.SET_CONFIRM_REVIEW('review');
            this.SET_PANCEL_DISABLED({ name: 'needInfo', disabled: true, });
            this.SET_PANCEL_DISABLED({ name: 'projectInfo', disabled: true, });
            this.SET_PANCEL_DISABLED({ name: 'researchInfo', disabled: true, });
            componentName = 'EditLookOrder';
            title = '评审方案';
            break;
          default:
            break;
        }
        this.panelArguments[componentName].props.title = title;
        this.panelArguments[componentName].props.showFooter = true;
        const width = this.getterPanelGroupData.demand ? drawerWidth.larger_pr : this.panelArguments[componentName][showState].width;
        this.renderPanelFn(
          componentName,
          width,
          this.panelArguments[componentName].props
        );
      } catch (error) {
        loading.close();
      }
    },

    async addProject() {
      await this.FETCH_PANEL_DATA({});
      this.SET_RESEARCH_INFO({});
      this.SET_LOOK_TASK(false);
      this.SET_ITEM_CODE('');
      this.SET_TASK_LIST([]);
      this.SET_PANCEL_DISABLED({ name: 'projectInfo', disabled: false, });
      this.panelArguments.ItemSet.props.title = '新增项目';
      this.panelArguments.ItemSet.width = drawerWidth.mini_px;
      this.panelArguments.ItemSet.props.showFooter = true;
      this.panelArguments.ItemSet.props.showTimeLine = false;

      this.SET_TASK_PERMISSION_NAME('leader');
      this.renderPanelFn(
        'ItemSet',
        this.panelArguments.ItemSet.width,
        this.panelArguments.ItemSet.props
      );
    },
    changeProcess(type) {
      this.queryCondition.code = type;
      this.currentPage = 1;
      this.queryCondition.pageNum = this.currentPage;
      this.fetchData();
    },

    /**
     * 渲染各种面板
     */
    renderPanelFn(componentName, width, props) {
      const self = this;
      this.$drawer({
        width: width,
        component: () => {
          return self.$createElement(componentName, {
            props: props,
            on: {
              done: () => {
                self.onDone();
              },
              save: () => {
                self.onDone();
              },
            },
          });
        },
      });
    },

    filterChange(val) {
      for (const i in val) {
        if (i === 'joinUser') {
          this.queryCondition['users'] = arrayToString(val[i]);
        } else {
          this.queryCondition[i] = arrayToString(val[i]);
        }
      }
      this.currentPage = 1;
      this.queryCondition.pageNum = this.currentPage;
      this.fetchData();
    },
  },
};
</script>

<style lang="scss" scoped>
.setUp_aside {
  background: #fff;
}
.p-16 {
  padding: 0 16px;
}
.approval-main-header {
  line-height: 60px;
  height: 60px;
  min-height: 60px;
}
.setUp-bottom_container {
  background: rgb(255, 255, 255);
  // margin-left: 12px;
}
.pagination-container {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

</style>
